<?php
require_once dirname(__FILE__) . '/includes/common.inc.php';
require_once dirname(__FILE__) . "/database/$database/database.inc.php";

header('Content-Type: text/plain');

global $myManager;

try {
  $hostname = HOST_NAME;
  $username = USER_NAME2;
  $password = PASSWORD2;
  $dbname = DATABASE_NAME2;
  $myPdo = new PDO ('mysql:host=' . $hostname, $username, $password);
  $myPdo->exec('USE ' . $dbname);
  $myPdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
  echo $e->getMessage ();
}


//$orm1 = classToOrm('produceselect');
try {
  $stmt = $myPdo->prepare("SELECT e.e_oid AS id, 
                                  tr.sourceId as sourceId, tr.targetId as targetId
                           FROM ns_ProduceEvent AS e LEFT JOIN ns__ez_relation_produceevent_producetransition AS pt ON e.e_oid = pt.oid_a 
                                                     LEFT JOIN ns_ProduceTransition AS tr ON tr.e_oid = pt.oid_b
                          ");
  $stmt->execute();
  
  //$myManager->start_t();
  $myPdo->beginTransaction();
  $i = 0;
  while ($i < $stmt->rowCount()) {
    $event = $stmt->fetch(PDO::FETCH_OBJ);
    
    $sql = "";
    if (isset($event->sourceId) &&
        isset($event->targetId)) {
      $sql .= (empty($sql) ? "" : ", ") . "sourceId = '" . $event->sourceId . "'";
      $sql .= (empty($sql) ? "" : ", ") . "targetId = '" . $event->targetId . "'";
    }

    if (!empty($sql)) {
      $myPdo->exec("UPDATE ns_ProduceEvent SET $sql WHERE e_oid = $event->id");
    }
    $i++;
  }
  $myPdo->commit();
  
  echo json_encode(array());
} catch (PDOException $e) {
  $myPdo->rollBack();
  echo $e->getMessage();
}
?>